var express = require('express');
var router = express.Router();
const {permissionModel, roleModel, userModel,role_perm_Model} = require('../model/model')
const jwt = require('jsonwebtoken')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 登录 生成token
router.post('/login', async (req, res) => {
  let body = req.body
  let data = await userModel.findOne({$and: [{username: body.username},{password: body.password}]},{password:0}).exec()
  if (!data){
    res.send({status: 404, msg:'账号或密码错误！'})
  }else if(!data.mg_state){
    res.send({status: 403, msg: '此账号目前无法登录！'})
  }else{
    let user = {username: data.username}
    let token = 'Bearer' + ' ' + jwt.sign(user, 'flag')
    await userModel.updateOne({username: user.username}, {token})
    res.send({data, token, status: 201, msg: '登录成功！'})
  }
  
})

// 用户

// 展示用户
router.get('/user', async (req, res) => {
  let page = parseInt(req.query.page)
  let pagesize = parseInt(req.query.pagesize)
  let search = req.query.search
  let data = ''
  let total = 0
  if (search){
    let reg = RegExp(search)
    data = await userModel.find({username: reg},{password:0}).populate('role_id').limit(pagesize).skip((page-1) * pagesize).exec()
    let count = await userModel.find({username: reg}).exec()
    total = count.length
  }else{
    data = await userModel.find({},{password:0}).populate('role_id').limit(pagesize).skip((page-1) * pagesize).exec()
    total = await userModel.count()
  }
  res.send({data, total})
})

// 添加用户
router.post('/user', async (req, res) => {
  let body = req.body
  let data = await userModel.create(body)
  res.send(data)
})

// 修改用户状态
router.patch('/user/state/:id', async (req, res) =>{
  let _id = req.params.id
  let mg_state = req.body.mg_state
  await userModel.updateOne({_id},{mg_state})
  res.send({'msg':"成功"})
})

// 删除用户
router.delete('/user/:id', async (req, res) => {
  let _id = req.params.id
  await userModel.deleteOne({_id})
  res.send({})
})

// 修改用户
router.patch('/user/:id', async ( req , res ) => {
  let _id = req.params.id
  let body = req.body
  await userModel.updateOne({_id}, body)
  res.send({'msg':'修改成功！'})
} )

// 分配角色
router.patch('/setRoles/:id', async(req, res) => {
  let _id = req.params.id
  let role_id = req.body.role_id
  await userModel.updateOne({_id},{role_id})
  res.send({msg:'分配成功！'})
})



// 角色

// 获取角色列表
router.get('/roles', async(req, res) => {
  let data = await roleModel.find().exec()
  for (const item of data) {
    item._doc.perms = []
    let permData = await role_perm_Model.find({roleid: item._id}).populate('permid').exec()
    if (permData.length){
      let perm = permData.filter(permitem => permitem.permid.permission_level === 0)
      let subperm = permData.filter(permitem => permitem.permid.permission_level === 1)
      for (const subitem of perm) {
        subitem.permid._doc.children = []
        for (const sonitem of subperm) {
          if (subitem.permid._id == sonitem.permid.parent_id){
            subitem.permid._doc.children.push(sonitem.permid)
          }
        }
        item._doc.perms.push(subitem.permid)
      }
    }
  }
  res.send(data)
})


// 添加角色
router.post('/roles', async (req, res) => {
  let body = req.body
  let data = await roleModel.create(body)
  res.send(data)
})


// 删除角色
router.delete('/roles/:id', async (req, res) => {
  let _id = req.params.id
  await roleModel.deleteOne({_id})
  res.send({})
})

// 修改角色
router.patch('/roles/:id', async (req, res) => {
  let _id = req.params.id
  let body = req.body
  await roleModel.updateOne({_id}, body)
  res.send({msg:'成功！'})
})


// 获取角色对应的权限列表
router.get('/role_perm/:id', async (req, res) => {
  let roleid = req.params.id
  let data = await role_perm_Model.find({roleid}).populate('permid').exec()
  res.send(data)
})


// 分配权限
router.patch('/setRole/:id', async (req, res) => {
  let data = req.body.data
  let roleid = req.params.id
  await role_perm_Model.deleteMany({roleid})
  for (const item of data) {
    await role_perm_Model.create({roleid, permid: item})
  }
  res.send({msg: '分配成功！', status: 201})
})

// 删除角色对应权限
router.post('/delRole/:id', async (req, res) => {
  let roleid = req.params.id
  let arr = req.body.rightlist
  for (const item of arr) {
    await role_perm_Model.deleteOne({$and: [{roleid},{permid: item}]})
  }
  res.send({status: 200})
})



// 权限

// 权限列表  普通展示或者分配权限时作展示使用此路由
router.get('/permission/:type', async (req, res) =>{
  let type = req.params.type
  let data = []
  if (type === 'tree'){
    data = await permissionModel.find({permission_level: 0}).exec()
    let subdata = await permissionModel.find({permission_level:1}).exec()
    data.forEach(item => {
      item._doc.children = []
      subdata.forEach(subitem => {
        if (subitem.parent_id == item._id){
          item._doc.children.push(subitem)
        }
      })
    })
  }else if(type === 'list'){
    data = await permissionModel.find({}).exec()
  }
  res.send(data)
})


// 获取用户对应 权限列表  作菜单栏
router.get('/menu/:id',async (req, res) => {
  let _id = req.params.id
  let roledata = await userModel.findOne({_id}).exec()
  let roleid = roledata.role_id
  let data = []
  let permData = await role_perm_Model.find({roleid}).populate('permid').exec()
  if (permData.length){
    let perm = permData.filter(permitem => permitem.permid.permission_level === 0)
    let subperm = permData.filter(permitem => permitem.permid.permission_level === 1)
    for (const subitem of perm) {
      subitem.permid._doc.children = []
      for (const sonitem of subperm) {
        if (subitem.permid._id == sonitem.permid.parent_id){
          subitem.permid._doc.children.push(sonitem.permid)
        }
      }
      data.push(subitem.permid)
    }
  }
  res.send({data, status: 200})
})


module.exports = router;
